package cc.ufinity.networkdiagnose.widget;

import java.util.ArrayList;
import java.util.Map;

import android.app.Activity;
import android.graphics.Color;
import android.net.wifi.ScanResult;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import cc.ufinity.networkdiagnose.app.GlobalApp;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.NetworkManager;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.Task.PingTask;
import cc.ufinity.networkdiagnose.manager.WlanManager;
import cc.ufinity.networkdiagnose.util.StringUtils;
import cc.ufinity.networkdiagnose.util.StringUtils.PING_RESULT;
import cc.ufinity.networkdiagnose.view.R;

public class PingWidget extends GeneralTestWidget {

	private WlanManager wlanManager;
    private ScrollView pingSv;
    private LinearLayout pingRsLayout;
    private Activity ctx;
    private Handler handler;
    private Button backBtn;
    private Button startBtn;
    private Button btnRetest;
    private NetworkManager nm;
    private EditText et;
    private Task task;
    
    private final String defaultPing = "www.baidu.com";
    private boolean isPingOver = true;

    public PingWidget(Activity context) {
        super(context);
        inflate(context, R.layout.ping, this);
        this.ctx = context;
        isPingOver = true;
        wlanManager = new WlanManager(ctx);
        pingSv = (ScrollView) this.findViewById(R.id.ping_test_ScrView);
        pingRsLayout = (LinearLayout) this.findViewById(R.id.pint_test_detail);
        backBtn = (Button) this.findViewById(R.id.ping_test_btnback);
        startBtn = (Button) this.findViewById(R.id.btn_ping_start);
     //   btnRetest = (Button) findViewById(R.id.btn_ping_retest);
        et = (EditText) this.findViewById(R.id.pingEditText);
        handler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case MessageWhat.WIFI_RECEIVE_LIST:
                    showWifiListDialog(ctx, wlanManager, handler);
                    dismissMessageDialog();
                    wlanManager.stopScan();
                    break;
                case MessageWhat.WIFI_SELECTED:
                    enableNetWork(selectedScanResult);
                    break;
                case MessageWhat.WIFI_SUCESS_CONNECTED:
                    dismissMessageDialog();
                    String ip = wlanManager.getIpAddress()==null?"":wlanManager.getIpAddress();
                    if(ip.length()>4 && ip.lastIndexOf(".")>0)
                    	ip = ip.substring(0,ip.lastIndexOf(".")+1);
                    String ApGateWay = wlanManager.getGateWay();
                    if (GlobalApp.DEBUG) {
                    	System.out.println("网关："+wlanManager.getGateWay());
					}
                    et.setText(ApGateWay);
                    et.setSelection(ApGateWay.length());
                    break;
                
                case MessageWhat.PING_SUCCESS:
                    update();
                    break;
                case MessageWhat.PING_FAILED:
                    showMessage(ctx, "PING测试失败，请返回重试！");
                    dismissMessageDialog();
                    isPingOver = true;
                    break;
                case MessageWhat.NETWORK_INVALID:
                    dismissMessageDialog();
                    showMessage(ctx, "无法连接至因特网.");
                    isPingOver = true;
                    break;
                }
            }
        };
        
        backBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
               // back(ctx);
            	switch(GlobalApp.nowNetType) {
				case 1:
					backToTestWidget_Wlan(ctx);
					break;
				case 2:
					backToTestWidget_TD(ctx);
					break;
				case 3:
					backToTestWidget_GSM(ctx);
					break;
				default:
					break;
				}
            }
        });
        startBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            	if(isPingOver) {
            		pingRsLayout.removeAllViews();
            		startPing();
            	} else {
            		showMessage(getContext(), "正在ping测试，请稍后再试");
            	}
            }
        });
        task = new Task();
        
        if(GlobalApp.nowNetType == 1) {
        	wlanManager.setHandler(handler);
            scanWifi();
        } else {
        	et.setText(defaultPing);
        }
        
    }
    
    private void enableNetWork(final ScanResult scan) {
        showMessageDialog(ctx, "正在连接Wifi热点...");
        new Thread() {
            public void run() {
                wlanManager.connect(scan);
            }
        }.start();

    }
    private void scanWifi() {
        showMessageDialog(ctx, "正在扫描附近Wifi热点...");
        new Thread() {
            public void run() {
                wlanManager.startScan();
            }
        }.start();
    }

    public void update() {
        TextView tv = new TextView(ctx);
        tv.setTextSize(12);
        tv.setText(StringUtils.pingResultToCh(nm.getPingResult()));
        tv.setTextColor(Color.BLACK);
        pingRsLayout.addView(tv);
        setScrollViewDown(pingSv);
        
        task.testCount = 10;
        PingTask pingTask = task.newPingTask("");
        Map<String, String> res = StringUtils.pingResult(nm.getPingResult());
        pingTask.bytes = res.get(PING_RESULT.PING_RESULT_BYTE_NO);
        pingTask.time = res.get(PING_RESULT.PING_RESULT_TIME);
        pingTask.ttl = res.get(PING_RESULT.PING_RESULT_TTL);
        ArrayList<PingTask> tasks = new ArrayList<PingTask>(1);
        tasks.add(pingTask);
        task.pingTasks = tasks;
        task.endTime = StringUtils.getDateTime();
        this.dismissMessageDialog();
        isPingOver = true;
    }

    public void startPing() {
        final String addr = et.getText().toString();

    	if (StringUtils.isEmpty(addr) && !addr.toLowerCase().startsWith("www.")
    			&& !addr.toLowerCase().startsWith("http://")) {
            this.showMessage(ctx, "请输入地址或IP.");
            return;
        }

        this.showMessageDialog(ctx, "正在进行Ping测试...");
        int type = NetworkManager.detectNetworkConnectivity(ctx);
        if (type == -1) {
            sendMsg(MessageWhat.NETWORK_INVALID, handler);
        } else {
            initTask(task, ctx, type);
            nm = new NetworkManager();
            nm.setHandler(handler);
            new Thread() {
                public void run() {
                    task.startTime = StringUtils.getDateTime();
                    nm.ping(addr, 10, 64);
                }
            }.start();
    		isPingOver = false;
        }

    }
}
